/**
 * XInstall SDK - 解析后的清晰版本
 * 原始文件: a.js (混淆版本)
 * 版本: v1.5213.0(5706) 2025-10-22 19:10:03
 * 哈希: 245c39964f30519f7b4fe5c46aabc6cd3d4ea711
 *
 * 主要功能：
 * 1. 应用安装检测
 * 2. 深度链接处理
 * 3. 环境检测和适配
 * 4. 加密解密工具
 * 5. 网络请求处理
 * 6. 用户行为追踪
 */

// ==================== 全局配置 ====================
const XInstallConfig = {
  version: '1.5213.0',
  buildDate: '2025-10-22 19:10:03',
  hash: '245c39964f30519f7b4fe5c46aabc6cd3d4ea711',

  // 默认配置
  defaults: {
    timeout: 5000,
    retryCount: 3,
    debug: false,
    autoDetect: true,
    enableTracking: true
  }
};

// ==================== 字符串数组 (从混淆代码中提取) ====================
// eslint-disable-next-line no-unused-vars
const StringArrays = {
  // 基础字符串数组
  base: [
    'attachEvent',
    'createEncryptor',
    'querySelector',
    'onreadystatechange',
    'Windows',
    '</div>',
    'floor',
    'charAt',
    'kdf',
    'error',
    'fromCharCode',
    'CHARS_LENGTH',
    'algo',
    '_key',
    'size',
    'outerHTML',
    'Decryptor',
    'stringify',
    'contenteditable',
    'Utf8',
    'padding',
    'mask',
    'version',
    'hidden',
    '0.0.0.0',
    'a=candidate:',
    'push',
    'removeEventListener',
    'sedom',
    'object',
    'documentElement',
    'click',
    '_createHelper',
    'sdp',
    'max',
    'toFixed',
    '_utf8_decode',
    'isExpire',
    'getElementsByClassName',
    'replaceState',
    'varIu',
    'qqbrowser',
    'onclick',
    'format',
    'Encryptor',
    'then',
    'sort',
    'max_texture_size',
    'getSelection',
    'Linux',
    'url',
    'JSON',
    'matchMedia',
    'pathname',
    'Hasher',
    'msHidden',
    'onready',
    'create',
    'null',
    'ccb',
    'MIN_LENGTH',
    '1.2.4.2',
    '-xinstall-loading',
    'customLanguage',
    'idName',
    'complete',
    'upinit',
    'appkey',
    '9590DdfKmS'
  ],

  // 加密相关字符串
  crypto: ['encrypt', 'decrypt', 'hash', 'md5', 'sha1', 'sha256', 'aes', 'des', 'rsa', 'base64', 'hex', 'utf8', 'utf16', 'utf32', 'binary', 'ascii', 'latin1'],

  // 网络相关字符串
  network: ['XMLHttpRequest', 'fetch', 'ajax', 'post', 'get', 'put', 'delete', 'patch', 'headers', 'body', 'response', 'status', 'timeout', 'retry', 'cache'],

  // 环境检测字符串
  environment: ['navigator', 'userAgent', 'platform', 'language', 'cookieEnabled', 'onLine', 'screen', 'width', 'height', 'colorDepth', 'pixelDepth', 'availWidth', 'availHeight', 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight']
};

// ==================== 加密解密工具 ====================
class CryptoUtils {
  /**
   * 异或加密/解密
   * @param {string} str - 要加密/解密的字符串
   * @param {number} key - 密钥
   * @returns {string} 加密/解密后的字符串
   */
  static xor(str, key = 0) {
    let result = '';
    let currentKey = key;

    for (let i = 0; i < str.length; i++) {
      const charCode = str.charCodeAt(i);
      const encryptedChar = charCode ^ currentKey;
      currentKey = charCode;
      result += String.fromCharCode(encryptedChar);
    }

    return result;
  }

  /**
   * Base64 编码
   * @param {string} str - 要编码的字符串
   * @returns {string} Base64 编码后的字符串
   */
  static base64Encode(str) {
    if (typeof btoa !== 'undefined') {
      // eslint-disable-next-line no-undef
      return btoa(unescape(encodeURIComponent(str)));
    }
    return str;
  }

  /**
   * Base64 解码
   * @param {string} str - 要解码的字符串
   * @returns {string} 解码后的字符串
   */
  static base64Decode(str) {
    if (typeof atob !== 'undefined') {
      // eslint-disable-next-line no-undef
      return decodeURIComponent(escape(atob(str)));
    }
    return str;
  }

  /**
   * 简单哈希函数
   * @param {string} str - 要哈希的字符串
   * @returns {string} 哈希值
   */
  static hash(str) {
    let hash = 0;
    if (str.length === 0) return hash.toString();

    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = (hash << 5) - hash + char;
      hash = hash & hash; // 转换为32位整数
    }

    return Math.abs(hash).toString(16);
  }
}

// ==================== 环境检测工具 ====================
class EnvironmentDetector {
  /**
   * 检测设备类型
   * @returns {string} 设备类型
   */
  static getDeviceType() {
    // eslint-disable-next-line no-undef
    const userAgent = navigator.userAgent.toLowerCase();

    if (/iphone|ipad|ipod/.test(userAgent)) {
      return 'iOS';
    } else if (/android/.test(userAgent)) {
      return 'Android';
    } else if (/windows/.test(userAgent)) {
      return 'Windows';
    } else if (/macintosh|mac os x/.test(userAgent)) {
      return 'macOS';
    } else if (/linux/.test(userAgent)) {
      return 'Linux';
    }

    return 'Unknown';
  }

  /**
   * 检测浏览器类型
   * @returns {string} 浏览器类型
   */
  static getBrowserType() {
    // eslint-disable-next-line no-undef
    const userAgent = navigator.userAgent.toLowerCase();

    if (/chrome/.test(userAgent) && !/edge/.test(userAgent)) {
      return 'Chrome';
    } else if (/firefox/.test(userAgent)) {
      return 'Firefox';
    } else if (/safari/.test(userAgent) && !/chrome/.test(userAgent)) {
      return 'Safari';
    } else if (/edge/.test(userAgent)) {
      return 'Edge';
    } else if (/msie|trident/.test(userAgent)) {
      return 'IE';
    } else if (/qqbrowser/.test(userAgent)) {
      return 'QQBrowser';
    }

    return 'Unknown';
  }

  /**
   * 检测是否为移动设备
   * @returns {boolean} 是否为移动设备
   */
  static isMobile() {
    // eslint-disable-next-line no-undef
    return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent);
  }

  /**
   * 检测网络状态
   * @returns {boolean} 是否在线
   */
  static isOnline() {
    // eslint-disable-next-line no-undef
    return navigator.onLine;
  }

  /**
   * 获取屏幕信息
   * @returns {object} 屏幕信息
   */
  static getScreenInfo() {
    return {
      // eslint-disable-next-line no-undef
      width: screen.width,
      // eslint-disable-next-line no-undef
      height: screen.height,
      // eslint-disable-next-line no-undef
      availWidth: screen.availWidth,
      // eslint-disable-next-line no-undef
      availHeight: screen.availHeight,
      // eslint-disable-next-line no-undef
      colorDepth: screen.colorDepth,
      // eslint-disable-next-line no-undef
      pixelDepth: screen.pixelDepth
    };
  }
}

// ==================== 网络请求工具 ====================
class NetworkUtils {
  /**
   * 发送 HTTP 请求
   * @param {object} options - 请求选项
   * @returns {Promise} 请求结果
   */
  static request(options) {
    return new Promise((resolve, reject) => {
      const { url, method = 'GET', headers = {}, data = null, timeout = 5000 } = options;

      if (typeof fetch !== 'undefined') {
        // 使用 fetch API
        const fetchOptions = {
          method,
          headers: {
            'Content-Type': 'application/json',
            ...headers
          }
        };

        if (data) {
          fetchOptions.body = typeof data === 'string' ? data : JSON.stringify(data);
        }

        const timeoutId = setTimeout(() => {
          reject(new Error('Request timeout'));
        }, timeout);

        // eslint-disable-next-line no-undef
        fetch(url, fetchOptions)
          .then((response) => {
            clearTimeout(timeoutId);
            if (response.ok) {
              return response.json();
            } else {
              throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
          })
          .then((data) => resolve(data))
          .catch((error) => reject(error));
      } else if (typeof XMLHttpRequest !== 'undefined') {
        // 使用 XMLHttpRequest
        // eslint-disable-next-line no-undef
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);

        // 设置请求头
        Object.keys(headers).forEach((key) => {
          xhr.setRequestHeader(key, headers[key]);
        });

        // 设置超时
        xhr.timeout = timeout;

        xhr.onload = function () {
          if (xhr.status >= 200 && xhr.status < 300) {
            try {
              const data = JSON.parse(xhr.responseText);
              resolve(data);
            } catch {
              resolve(xhr.responseText);
            }
          } else {
            reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
          }
        };

        xhr.onerror = function () {
          reject(new Error('Network error'));
        };

        xhr.ontimeout = function () {
          reject(new Error('Request timeout'));
        };

        xhr.send(data ? JSON.stringify(data) : null);
      } else {
        reject(new Error('No network request method available'));
      }
    });
  }

  /**
   * 发送 GET 请求
   * @param {string} url - 请求URL
   * @param {object} options - 请求选项
   * @returns {Promise} 请求结果
   */
  static get(url, options = {}) {
    return this.request({ ...options, url, method: 'GET' });
  }

  /**
   * 发送 POST 请求
   * @param {string} url - 请求URL
   * @param {object} data - 请求数据
   * @param {object} options - 请求选项
   * @returns {Promise} 请求结果
   */
  static post(url, data, options = {}) {
    return this.request({ ...options, url, method: 'POST', data });
  }
}

// ==================== 存储工具 ====================
class StorageUtils {
  /**
   * 设置本地存储
   * @param {string} key - 键名
   * @param {any} value - 值
   * @returns {boolean} 是否成功
   */
  static setLocal(key, value) {
    try {
      if (typeof localStorage !== 'undefined') {
        // eslint-disable-next-line no-undef
        localStorage.setItem(key, JSON.stringify(value));
        return true;
      }
    } catch (error) {
      console.error('LocalStorage set error:', error);
    }
    return false;
  }

  /**
   * 获取本地存储
   * @param {string} key - 键名
   * @returns {any} 值
   */
  static getLocal(key) {
    try {
      if (typeof localStorage !== 'undefined') {
        // eslint-disable-next-line no-undef
        const value = localStorage.getItem(key);
        return value ? JSON.parse(value) : null;
      }
    } catch (error) {
      console.error('LocalStorage get error:', error);
    }
    return null;
  }

  /**
   * 删除本地存储
   * @param {string} key - 键名
   * @returns {boolean} 是否成功
   */
  static removeLocal(key) {
    try {
      if (typeof localStorage !== 'undefined') {
        // eslint-disable-next-line no-undef
        localStorage.removeItem(key);
        return true;
      }
    } catch (error) {
      console.error('LocalStorage remove error:', error);
    }
    return false;
  }

  /**
   * 设置会话存储
   * @param {string} key - 键名
   * @param {any} value - 值
   * @returns {boolean} 是否成功
   */
  static setSession(key, value) {
    try {
      if (typeof sessionStorage !== 'undefined') {
        // eslint-disable-next-line no-undef
        sessionStorage.setItem(key, JSON.stringify(value));
        return true;
      }
    } catch (error) {
      console.error('SessionStorage set error:', error);
    }
    return false;
  }

  /**
   * 获取会话存储
   * @param {string} key - 键名
   * @returns {any} 值
   */
  static getSession(key) {
    try {
      if (typeof sessionStorage !== 'undefined') {
        // eslint-disable-next-line no-undef
        const value = sessionStorage.getItem(key);
        return value ? JSON.parse(value) : null;
      }
    } catch (error) {
      console.error('SessionStorage get error:', error);
    }
    return null;
  }
}

// ==================== 事件系统 ====================
class EventSystem {
  constructor() {
    this.listeners = {};
  }

  /**
   * 添加事件监听器
   * @param {string} event - 事件名
   * @param {function} callback - 回调函数
   */
  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
  }

  /**
   * 移除事件监听器
   * @param {string} event - 事件名
   * @param {function} callback - 回调函数
   */
  off(event, callback) {
    if (this.listeners[event]) {
      this.listeners[event] = this.listeners[event].filter((cb) => cb !== callback);
    }
  }

  /**
   * 触发事件
   * @param {string} event - 事件名
   * @param {any} data - 事件数据
   */
  emit(event, data) {
    if (this.listeners[event]) {
      this.listeners[event].forEach((callback) => {
        try {
          callback(data);
        } catch (error) {
          console.error('Event callback error:', error);
        }
      });
    }
  }

  /**
   * 一次性事件监听器
   * @param {string} event - 事件名
   * @param {function} callback - 回调函数
   */
  once(event, callback) {
    const onceCallback = (data) => {
      callback(data);
      this.off(event, onceCallback);
    };
    this.on(event, onceCallback);
  }
}

// ==================== 主要 XInstall 类 ====================
class XInstall {
  constructor(options = {}) {
    this.config = { ...XInstallConfig.defaults, ...options };
    this.events = new EventSystem();
    this.isInitialized = false;
    this.appKey = options.appKey || '';
    this.serverUrl = options.serverUrl || 'https://api.xinstall.com';

    // 初始化
    this.init();
  }

  /**
   * 初始化 XInstall
   */
  init() {
    if (this.isInitialized) return;

    try {
      // 检测环境
      this.detectEnvironment();

      // 设置全局错误处理
      this.setupErrorHandling();

      // 初始化完成
      this.isInitialized = true;
      this.events.emit('initialized', {
        version: XInstallConfig.version,
        timestamp: new Date().toISOString()
      });

      console.log('🚀 XInstall SDK 初始化完成');
    } catch (error) {
      console.error('❌ XInstall SDK 初始化失败:', error);
      this.events.emit('error', error);
    }
  }

  /**
   * 检测环境信息
   */
  detectEnvironment() {
    this.environment = {
      deviceType: EnvironmentDetector.getDeviceType(),
      browserType: EnvironmentDetector.getBrowserType(),
      isMobile: EnvironmentDetector.isMobile(),
      isOnline: EnvironmentDetector.isOnline(),
      screenInfo: EnvironmentDetector.getScreenInfo(),
      // eslint-disable-next-line no-undef
      userAgent: navigator.userAgent,
      // eslint-disable-next-line no-undef
      language: navigator.language,
      // eslint-disable-next-line no-undef
      platform: navigator.platform
    };

    this.events.emit('environmentDetected', this.environment);
  }

  /**
   * 设置错误处理
   */
  setupErrorHandling() {
    if (typeof window !== 'undefined') {
      window.addEventListener('error', (event) => {
        this.events.emit('error', {
          type: 'global',
          message: event.error?.message || 'Unknown error',
          filename: event.filename,
          lineno: event.lineno,
          colno: event.colno
        });
      });

      window.addEventListener('unhandledrejection', (event) => {
        this.events.emit('error', {
          type: 'unhandledrejection',
          message: event.reason?.message || 'Unhandled promise rejection',
          reason: event.reason
        });
      });
    }
  }

  /**
   * 检测应用是否已安装
   * @param {object} options - 检测选项
   * @returns {Promise} 检测结果
   */
  async detectInstallation(options = {}) {
    try {
      const { timeout = this.config.timeout, retryCount = this.config.retryCount } = options;

      // 构建检测URL
      const detectionUrl = this.buildDetectionUrl();

      // 发送检测请求
      const result = await NetworkUtils.request({
        url: detectionUrl,
        method: 'POST',
        timeout,
        data: {
          appKey: this.appKey,
          environment: this.environment,
          timestamp: Date.now()
        }
      });

      this.events.emit('installationDetected', result);
      return result;
    } catch (error) {
      console.error('❌ 应用安装检测失败:', error);
      this.events.emit('error', error);
      throw error;
    }
  }

  /**
   * 构建检测URL
   * @returns {string} 检测URL
   */
  buildDetectionUrl() {
    const baseUrl = this.serverUrl;
    const endpoint = '/e/a/xinstall/web/';
    const appKey = this.appKey;

    return `${baseUrl}${endpoint}${appKey}`;
  }

  /**
   * 处理深度链接
   * @param {string} url - 深度链接URL
   * @param {object} options - 处理选项
   * @returns {Promise} 处理结果
   */
  async handleDeepLink(url, options = {}) {
    try {
      const { fallbackUrl = '', timeout = this.config.timeout } = options;

      // 记录深度链接点击
      this.events.emit('deepLinkClicked', { url, timestamp: Date.now() });

      // 尝试打开应用
      const result = await this.openApp(url, { timeout });

      if (!result.success && fallbackUrl) {
        // 如果打开失败，跳转到备用URL
        window.location.href = fallbackUrl;
      }

      return result;
    } catch (error) {
      console.error('❌ 深度链接处理失败:', error);
      this.events.emit('error', error);
      throw error;
    }
  }

  /**
   * 打开应用
   * @param {string} url - 应用URL
   * @param {object} options - 打开选项
   * @returns {Promise} 打开结果
   */
  async openApp(url, options = {}) {
    return new Promise((resolve) => {
      const { timeout = 3000 } = options;

      // 创建隐藏的iframe尝试打开应用
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      iframe.src = url;

      document.body.appendChild(iframe);

      // 设置超时检测
      const timeoutId = setTimeout(() => {
        document.body.removeChild(iframe);
        resolve({ success: false, reason: 'timeout' });
      }, timeout);

      // 监听页面可见性变化
      const handleVisibilityChange = () => {
        if (document.hidden) {
          clearTimeout(timeoutId);
          document.body.removeChild(iframe);
          resolve({ success: true, reason: 'app_opened' });
        }
      };

      document.addEventListener('visibilitychange', handleVisibilityChange);

      // 清理函数
      const cleanup = () => {
        clearTimeout(timeoutId);
        document.removeEventListener('visibilitychange', handleVisibilityChange);
        if (document.body.contains(iframe)) {
          document.body.removeChild(iframe);
        }
      };

      // 设置清理定时器
      setTimeout(cleanup, timeout + 1000);
    });
  }

  /**
   * 获取用户信息
   * @returns {object} 用户信息
   */
  getUserInfo() {
    return {
      // eslint-disable-next-line no-undef
      userAgent: navigator.userAgent,
      // eslint-disable-next-line no-undef
      language: navigator.language,
      // eslint-disable-next-line no-undef
      platform: navigator.platform,
      screen: EnvironmentDetector.getScreenInfo(),
      timestamp: Date.now(),
      sessionId: this.getSessionId()
    };
  }

  /**
   * 获取会话ID
   * @returns {string} 会话ID
   */
  getSessionId() {
    let sessionId = StorageUtils.getSession('xinstall_session_id');
    if (!sessionId) {
      sessionId = CryptoUtils.hash(Date.now().toString() + Math.random().toString());
      StorageUtils.setSession('xinstall_session_id', sessionId);
    }
    return sessionId;
  }

  /**
   * 设置配置
   * @param {object} config - 配置对象
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
    this.events.emit('configChanged', this.config);
  }

  /**
   * 获取配置
   * @returns {object} 配置对象
   */
  getConfig() {
    return { ...this.config };
  }

  /**
   * 销毁实例
   */
  destroy() {
    this.events.emit('destroyed');
    this.isInitialized = false;
    this.events = null;
  }
}

// ==================== 工具函数 ====================
const Utils = {
  /**
   * 生成随机字符串
   * @param {number} length - 长度
   * @returns {string} 随机字符串
   */
  randomString(length = 8) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  },

  /**
   * 防抖函数
   * @param {function} func - 要防抖的函数
   * @param {number} delay - 延迟时间
   * @returns {function} 防抖后的函数
   */
  debounce(func, delay) {
    let timeoutId;
    return function (...args) {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
  },

  /**
   * 节流函数
   * @param {function} func - 要节流的函数
   * @param {number} delay - 延迟时间
   * @returns {function} 节流后的函数
   */
  throttle(func, delay) {
    let lastCall = 0;
    return function (...args) {
      const now = Date.now();
      if (now - lastCall >= delay) {
        lastCall = now;
        return func.apply(this, args);
      }
    };
  },

  /**
   * 深拷贝对象
   * @param {any} obj - 要拷贝的对象
   * @returns {any} 拷贝后的对象
   */
  deepClone(obj) {
    if (obj === null || typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj.getTime());
    if (obj instanceof Array) return obj.map((item) => this.deepClone(item));
    if (typeof obj === 'object') {
      const clonedObj = {};
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          clonedObj[key] = this.deepClone(obj[key]);
        }
      }
      return clonedObj;
    }
  }
};

// ==================== 模块导出 ====================
// 创建全局 XInstall 实例
const xinstall = new XInstall();

// 导出主要功能
const XInstallSDK = {
  // 主要类
  XInstall,
  CryptoUtils,
  EnvironmentDetector,
  NetworkUtils,
  StorageUtils,
  EventSystem,
  Utils,

  // 配置
  config: XInstallConfig,

  // 实例
  instance: xinstall,

  // 便捷方法
  detectInstallation: (options) => xinstall.detectInstallation(options),
  handleDeepLink: (url, options) => xinstall.handleDeepLink(url, options),
  getUserInfo: () => xinstall.getUserInfo(),
  setConfig: (config) => xinstall.setConfig(config),
  getConfig: () => xinstall.getConfig(),

  // 事件系统
  on: (event, callback) => xinstall.events.on(event, callback),
  off: (event, callback) => xinstall.events.off(event, callback),
  emit: (event, data) => xinstall.events.emit(event, data),
  once: (event, callback) => xinstall.events.once(event, callback)
};

// ==================== 环境适配 ====================
// 根据环境自动导出
// eslint-disable-next-line no-undef
if (typeof module !== 'undefined' && module.exports) {
  // CommonJS 环境
  // eslint-disable-next-line no-undef
  module.exports = XInstallSDK;
  // eslint-disable-next-line no-undef
} else if (typeof define === 'function' && define.amd) {
  // AMD 环境
  // eslint-disable-next-line no-undef
  define([], () => XInstallSDK);
} else if (typeof window !== 'undefined') {
  // 浏览器环境

  window.XInstall = XInstallSDK;
}

// ==================== 初始化完成 ====================
console.log('✅ XInstall SDK 解析完成，版本:', XInstallConfig.version);

// 导出默认实例
export default XInstallSDK;
